package com.gzy.wb.controller;

import com.gzy.wb.core.R;
import org.apache.tomcat.jni.OS;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.UUID;

import org.springframework.core.io.Resource;

@RestController
public class FileController {

    String uploadDir = "E:\\lxf\\uploadfile";

    @PostMapping("/uploadfile")
    R<String> uploadFile(@RequestParam(name = "file") MultipartFile file) {

        if (file.isEmpty()){
            return new R<>(){{
                setCode(Code.ERR);
                setMessage("文件不存在");
            }};
        }
        File dir = new File(uploadDir);
        if (!dir.exists()){
            dir.mkdir();
        }

        String ex = "temp";
        String[] split = file.getOriginalFilename().split("\\.");
        if (split.length != 0){
            ex = split[split.length-1];
        }

        String uuid = UUID.randomUUID().toString();
        String filename = uuid + "." + ex;

//        file.transferTo();
        try {
            file.transferTo(new File(uploadDir + "/" + filename));
        } catch (IOException e) {
            e.printStackTrace();
            return new R<>() {
                {
                    setCode(Code.ERR);
                    setMessage("保存失败");
                }
            };
        }


        return new R<>() {
            {
                setMessage("ok");
                setData(filename);
            }
        };
    }

    @GetMapping("/downloadFile/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request,HttpServletResponse response) {
        File file = new File(uploadDir + "/" + fileName);
        if(!file.exists()){
            return null;
        }
        try {
            UrlResource resource = new UrlResource(file.toURI());
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }


}
